package com.lsh.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/8/16 5:13 下午
 * @desc ：自定义路由过滤器  参考StripPrefixGatewayFilterFactory
 */
@Component
public class RequestPathGatewayFilterFactory
        extends AbstractGatewayFilterFactory<RequestPathGatewayFilterFactory.Config> {

    public RequestPathGatewayFilterFactory() {
        super(Config.class);
    }

    //如果可以简化配置方案，当前方法返回简化配置参数命名列表
    // RequestPath=NameValue,PathValue
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name","path");
    }

    //过滤逻辑
    @Override
    public GatewayFilter apply(Config config) {
        //匿名内部类
        return new GatewayFilter() {
            //过滤方法
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String path = exchange.getRequest().getPath().toString();
                System.out.println("路由过滤器：本次请求地址为："+path+",配置的参数为：name:"+config.getName()+",path:"+config.getPath());
                //写在chain.filter(exchange)之前的前置过滤，之后的后置过滤
                Mono<Void> filter = chain.filter(exchange);

                return filter;
            }
        };
    }
    //内部类
    //当前过滤器需要使用的配置内容
     public static class Config{

        private String name;

        private String path;

        //Get / Set 方法
        public String getName() {
            return name;
        }

        public Config setName(String name) {
            this.name = name;
            return this;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }
    }
}
